import React, {Component} from 'react';
import {
  StyleSheet,
  StatusBar,
  View,
  Text,
  ImageBackground,
  TouchableOpacity,
  ToastAndroid,
} from 'react-native';
import {connect} from 'react-redux';
import {Icon, InputItem, Button, Toast} from '@ant-design/react-native';
import {pxToDp} from '../../utils/stylesKits';
import {setUserInfo} from '../../store/actions';
import loginBgImage from '../../assets/image/profileBackground.jpg';
import {sendVerifyCode, login} from '../../api/login';
import {isPhone} from '../../utils/validate';
import storage from '../../utils/storage';

/**
 * APP Login 页面
 * */

let timer = null;
let time = 60;

export class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      phone: '',
      verifyCode: '',
      isPhoneError: false,
      isSendVerifyCode: false,
      time: 60,
    };
  }

  /**
   * 渲染发送验证码按钮
   */

  renderVerifyCodeBtn = () => {
    return (
      <Button
        style={styles.verifyCodeBtn}
        disabled={this.state.isSendVerifyCode}
        onPress={this.sendVerifyCode}>
        {this.state.isSendVerifyCode
          ? `${this.state.time}秒后再试`
          : '获取验证码'}
      </Button>
    );
  };

  /**
   * 发送验证码
   */

  sendVerifyCode = async () => {
    if (!this.state.phone) {
      Toast.fail('请输入手机号码', 2, null, false);
      return;
    }
    if (!isPhone(this.state.phone)) {
      this.setState(() => {
        return {isPhoneError: true};
      });
      return;
    }
    this.setState(() => {
      return {isSendVerifyCode: true};
    });
    timer = setInterval(() => {
      if (this.state.time < 1) {
        clearInterval(timer);
        this.setState(() => {
          return {isSendVerifyCode: false};
        });
      } else {
        time--;
        this.setState(() => {
          return {time: time};
        });
      }
    }, 1000);
    const data = {
      phone: this.state.phone,
    };
    const res = await sendVerifyCode(data);
    if (res.status !== 200) {
      this.setState(() => {
        return {isSendVerifyCode: false};
      });
      Toast.fail(res.msg, 2, null, false);
      return;
    }
    ToastAndroid.show(res.data, ToastAndroid.SHORT); // 由于后端并没有真正发送验证码给手机，所以直接给你看一下
    Toast.success('发送成功！请注意查收', 2, null, false);
  };

  /**
   * 登陆
   */

  login = async () => {
    if (!this.state.phone) {
      Toast.fail('请输入手机号码', 2, null, false);
      return;
    }
    if (!this.state.verifyCode) {
      Toast.fail('请输入验证码', 2, null, false);
      return;
    }
    if (!isPhone(this.state.phone)) {
      this.setState(() => {
        return {isPhoneError: true};
      });
      return;
    }
    const data = {
      phone: this.state.phone,
      verifyCode: this.state.verifyCode,
    };
    let logining = Toast.loading('请稍等...', 8);
    const res = await login(data);
    Toast.remove(logining);
    if (res.status !== 200) {
      Toast.fail(res.msg, 2, null, false);
      return;
    }
    Toast.success('登陆成功', 2, null, false);
    storage.save({
      key: 'userInfo',
      data: res.data,
    });
    this.props.setUserInfo({userInfo: res.data});
    this.props.navigation.goBack();
  };

  componentDidMount() {}

  componentDidUpdate(prevProps, prevState) {}

  componentWillUnmount() {
    clearInterval(timer);
  }

  render() {
    return (
      <View style={styles.container}>
        <StatusBar backgroundColor="transparent" translucent={true} />
        <ImageBackground source={loginBgImage} style={styles.loginBgImage}>
          <TouchableOpacity
            style={styles.back}
            onPress={() => this.props.navigation.goBack()}>
            <Icon name="arrow-left" color="#ffffff" />
            <Text style={styles.text}>返回</Text>
          </TouchableOpacity>
        </ImageBackground>
        <Text style={styles.title}>您好，欢迎回来！</Text>
        <View>
          <Text style={styles.inputLable}>手机号码：</Text>
          <InputItem
            clear
            type="number"
            maxLength={11}
            placeholder="手机号码"
            placeholderTextColor="#cdcdcd"
            value={this.state.phone}
            style={styles.inputItemPhone}
            error={this.state.isPhoneError}
            onErrorClick={() => Toast.fail('手机号码格式错误', 2, null, false)}
            onChange={value => {
              this.setState({
                phone: value,
              });
            }}
          />
        </View>
        <View>
          <Text style={styles.inputLable}>验证码：</Text>
          <InputItem
            type="number"
            maxLength={4}
            placeholder="验证码"
            placeholderTextColor="#cdcdcd"
            value={this.state.verifyCode}
            style={styles.inputItemVerifyCode}
            extra={this.renderVerifyCodeBtn()}
            onChange={value => {
              this.setState({
                verifyCode: value,
              });
            }}
          />
        </View>
        <View style={styles.loginBtnView}>
          <Button style={styles.loginBtn} onPress={this.login}>
            <Icon name="arrow-right" color="#ffffff" />
          </Button>
        </View>
      </View>
    );
  }
}

const mapStateToProps = state => ({});
const mapDispatchToProps = dispatch => {
  return {
    setUserInfo: userInfo => {
      dispatch(setUserInfo(userInfo));
    },
  };
};

const styles = StyleSheet.create({
  container: {
    width: '100%',
    height: '100%',
    backgroundColor: '#f1f1f1',
  },
  text: {
    color: '#ffffff',
    fontSize: 21,
    marginLeft: pxToDp(5),
  },
  loginBgImage: {
    width: '100%',
    height: pxToDp(200),
  },
  back: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: pxToDp(20),
    paddingTop: pxToDp(65),
    paddingBottom: pxToDp(100),
    color: '#010101',
    opacity: 0.6,
  },
  title: {
    color: '#010101',
    fontSize: 28,
    marginTop: pxToDp(25),
    marginLeft: pxToDp(45),
  },
  inputLable: {
    marginTop: pxToDp(25),
    marginLeft: pxToDp(60),
    marginBottom: pxToDp(5),
    fontSize: 18,
    opacity: 0.7,
    color: '#010101',
  },
  inputItemPhone: {
    color: '#010101',
    backgroundColor: '#f1f1f1',
    marginLeft: pxToDp(25),
    marginRight: pxToDp(25),
    paddingLeft: pxToDp(20),
    paddingRight: pxToDp(20),
    borderWidth: pxToDp(1),
    borderColor: '#bababa',
    borderRadius: pxToDp(25),
  },
  inputItemVerifyCode: {
    color: '#010101',
    backgroundColor: '#f1f1f1',
    marginLeft: pxToDp(25),
    paddingLeft: pxToDp(20),
    paddingRight: pxToDp(20),
    borderWidth: pxToDp(1),
    borderColor: '#bababa',
    borderRightWidth: 0,
    borderTopLeftRadius: pxToDp(25),
    borderBottomLeftRadius: pxToDp(25),
  },
  verifyCodeBtn: {
    height: pxToDp(46),
    borderColor: '#bababa',
    marginRight: pxToDp(25),
    borderTopLeftRadius: 0,
    borderBottomLeftRadius: 0,
  },
  loginBtnView: {
    alignItems: 'flex-end',
    padding: pxToDp(40),
  },
  loginBtn: {
    width: pxToDp(60),
    height: pxToDp(60),
    borderRadius: pxToDp(30),
    backgroundColor: '#3347b8',
  },
});

export default connect(mapStateToProps, mapDispatchToProps)(Login);
